<?php defined('SYSPATH') OR die('No direct access allowed.');

class User_Controller extends Crud_Controller {

	protected $form_criar = array(
	        'username'	=> '',
	        'password'	=> '',
	        'repassword'=> '',
			'active'	=> '1',
			'roles'		=> '1',
	);

	public function __construct(){
		parent::__construct(); // This must be included
	}

	public function index(){
		url::redirect('user/listar');
	}

	public function listar($pg_num=0, $msg=""){
		$total_items = ORM::factory('user')->count_all();
		$this->pagination = new Pagination(array(
	        'base_url'    => 'user/listar/', // Set our base URL to controller 'items' and method 'page'
	        'uri_segment' => 'listar', // Our URI will look something like http://domain/items/page/19
	        'total_items' => $total_items // Total number of items.
		));
		$offset = $this->pagination->sql_offset;
		$itens_por_pagina = $this->pagination->items_per_page;
		$users = ORM::factory('user')->find_all($itens_por_pagina,$offset);
		$this->create_view('user/list');
		$this->view->users = $users;
		$this->view->msg = $msg;
		$this->view->pagination = $this->pagination;
		$this->view->cabecalho->title .= '::Listar';
		$this->view->render(TRUE);
	}

	public function criar($msg=""){
		$this->create_view('user/criar');
		$this->view->msg = $msg;
		$this->view->roles = ORM::factory('auth_role')->select_list('id', 'name');
		$this->view->form = $this->form_criar;
		$this->view->cabecalho->title .= '::Criar';
		$this->view->render(TRUE);
	}

	public function salvar(){
		$acao = $this->input->post('acao');
		switch ($acao){
			case 'criar':
				$this->salvar_criar();
				break;
					
			case 'editar':
				$this->salvar_editar();
				break;
				
			case 'editar_senha':
				$this->salvar_editar_senha();
				break;
					
			case 'deletar':
				$this->salvar_deletar();
				break;
					
			default:
				break;
		}
	}

	private function salvar_criar(){
		$username	= $this->input->post('username');
		$password	= $this->input->post('password');
		$repassword = $this->input->post('repassword');
		$active		= $this->input->post('active');
		$roles 		= $this->input->post('roles');
		$regras_user = ORM::factory('user_negocio');
		if($regras_user->checarUsernameRepetido($username)){
			url::redirect('user/criar/'.Kohana::lang('user.e_usuario_existente'));
		}
		$validation = new Validation($this->input->post());
		$validation->pre_filter('trim', TRUE);
		$validation->add_rules('username','required', 'length[3,45]', 'alpha');
		$validation->add_rules('password', 'required', 'length[6,45]', 'alpha', 'matches[repassword]');
		$validation->add_rules('repassword', 'required', 'length[6,45]', 'alpha');
		$validation->add_rules('roles', 'required');
		if(!$validation->validate()){
			$msg = '';
			$erros = $validation->errors('form_error_messages');
			foreach($erros as $erro){
				$msg .= $erro;
			}
			$form = $validation->as_array();
			$this->create_view('user/criar');
			$this->view->msg = $msg;
			$this->view->roles = ORM::factory('auth_role')->select_list('id', 'name');
			$this->view->form = $form;
			$this->view->cabecalho->title .= '::Criar';
			$this->view->render(TRUE);
		}else{
			$user = ORM::factory('user');
			$user->username = $username;
			$user->password = md5($password);
			$user->active = $active;
			$user->deleted= 0;
			$user->auth_roles  = array($roles);
			$user->save();
			url::redirect('user/criar/'.Kohana::lang('user.i_salvo_sucesso'));
		}
	}

	private function salvar_editar(){
		$id 		= $this->input->post('id');
		$username	= $this->input->post('username');
		$active		= $this->input->post('active');
		$roles 		= $this->input->post('roles');
		$resultmsg = "";
		for ($i=0;$i<count($id); $i++){
			$user = ORM::factory('user', $id[$i]);
			$user->username = $username[$i];
			$user->active = $active[$i];
			$user->auth_roles  = array($roles[$i]);
			$user->save();
			$resultmsg .= $username[$i].':'.Kohana::lang('user.i_editado_sucesso');
		}
		url::redirect('user/listar/0/'.$resultmsg);
	}
	
	private function salvar_editar_senha(){
		$id 		= $this->input->post('id');
		$masterpassword	= $this->input->post('masterpassword');
		$password	= $this->input->post('password');
		$repassword	= $this->input->post('repassword');
		$thisuser = ORM::factory('user', $_SESSION['auth_user']);
		
		if($thisuser->password!=md5($masterpassword)){
			url::redirect('user/editar_senha/'.$id.'/digite sua senha');
		}
		if($password!=$repassword){
			url::redirect('user/editar_senha/'.$id.'/digite senhas iguais');
		}
			$user = ORM::factory('user', $id);
			$user->password = md5($password);
			$user->save();
		url::redirect('user/listar/');
	}
	
	private function salvar_deletar(){
		$id 		= $this->input->post('id');
		$username	= $this->input->post('username');
		$resultmsg = "";
		for ($i=0;$i<count($id); $i++){
			$user = ORM::factory('user', $id[$i]);
			$user->auth_roles = array();
			$user->delete();
			$resultmsg .= $username[$i].':'.Kohana::lang('user.i_deletado_sucesso');
		}
		url::redirect('user/listar/0/'.$resultmsg);
	}

	public function editar($msg=""){
		$pg_num = $this->input->post('pg_num');
		$validation = new Validation($this->input->post());
		$validation->add_rules('user_id','required');
		if(!$validation->validate()){
			url::redirect('user/listar/'.$pg_num);
		}
		$users_id = $this->input->post('user_id');
		$users = array();
		foreach ($users_id as $id){
			$users[] = ORM::factory('user', $id);
		}
		$this->create_view('user/editar');
		$this->view->msg = $msg;
		$this->view->roles = ORM::factory('auth_role')->select_list('id', 'name');
		$this->view->users = $users;
		$this->view->pg_num = $pg_num;
		$this->view->cabecalho->title .= '::Editar';
		$this->view->render(TRUE);
	}
	
	public function editar_senha($id, $msg=""){
		$user = ORM::factory('user', $id);
		$this->create_view('user/editar_senha');
		$this->view->msg = $msg;
		$this->view->user = $user;
		$this->view->cabecalho->title .= '::Editar Senha';
		$this->view->render(TRUE);
	}

	public function deletar($msg=""){
		$pg_num = $this->input->post('pg_num');
		$validation = new Validation($this->input->post());
		$validation->add_rules('user_id','required');
		if(!$validation->validate()){
			url::redirect('user/listar/'.$pg_num);
		}
		$users_id = $this->input->post('user_id');
		$users = array();
		foreach ($users_id as $id){
			$users[] = ORM::factory('user', $id);
		}
		$this->create_view('user/deletar');
		$this->view->msg = $msg;
		$this->view->users = $users;
		$this->view->pg_num = $pg_num;
		$this->view->cabecalho->title .= '::Deletar';
		$this->view->render(TRUE);
	}

	public function ver(){
		$pg_num = $this->input->post('pg_num');
		$validation = new Validation($this->input->post());
		$validation->add_rules('user_id','required');
		if(!$validation->validate()){
			url::redirect('user/listar/'.$pg_num);
		}
		$users_id = $this->input->post('user_id');
		$users = array();
		foreach ($users_id as $id){
			$users[] = ORM::factory('user', $id);
		}
		$this->create_view('user/ver');
		$this->view->users = $users;
		$this->view->pg_num = $pg_num;
		$this->view->cabecalho->title .= '::Ver';
		$this->view->render(TRUE);
	}

} // End Welcome Controller